/**
 * 内容管理API路由
 */

import { Router, Request, Response } from 'express';

const router = Router();

// 内容接口
interface Content {
  id: string;
  title: string;
  content: string;
  type: 'article' | 'video' | 'audio';
  authorId: string;
  authorName: string;
  authorAvatar: string;
  tags: string[];
  category: string;
  viewCount: number;
  likeCount: number;
  commentCount: number;
  shareCount: number;
  isLiked: boolean;
  isFavorited: boolean;
  publishTime: string;
  updateTime: string;
  status: 'draft' | 'published' | 'archived';
  coverImage?: string;
  summary?: string;
}

// 模拟内容数据
let contents: Content[] = [
  {
    id: '1',
    title: '新生儿护理完全指南',
    content: '新生儿护理是每个新手父母都需要掌握的重要技能...',
    type: 'article',
    authorId: 'expert1',
    authorName: '张医生',
    authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20doctor&image_size=square',
    tags: ['新生儿', '护理', '育儿'],
    category: '育儿知识',
    viewCount: 1250,
    likeCount: 89,
    commentCount: 23,
    shareCount: 15,
    isLiked: false,
    isFavorited: false,
    publishTime: '2024-01-15T10:00:00Z',
    updateTime: '2024-01-15T10:00:00Z',
    status: 'published',
    coverImage: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=newborn%20baby%20care&image_size=landscape_16_9',
    summary: '详细介绍新生儿护理的各个方面，包括喂养、睡眠、清洁等重要内容。'
  },
  {
    id: '2',
    title: '婴儿辅食添加时间表',
    content: '宝宝6个月后开始添加辅食，这是一个重要的成长阶段...',
    type: 'article',
    authorId: 'expert2',
    authorName: '李营养师',
    authorAvatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=nutritionist&image_size=square',
    tags: ['辅食', '营养', '6个月'],
    category: '营养喂养',
    viewCount: 980,
    likeCount: 67,
    commentCount: 18,
    shareCount: 12,
    isLiked: true,
    isFavorited: false,
    publishTime: '2024-01-14T14:30:00Z',
    updateTime: '2024-01-14T14:30:00Z',
    status: 'published',
    coverImage: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=baby%20food%20complementary&image_size=landscape_16_9',
    summary: '科学的辅食添加时间表，帮助宝宝健康成长。'
  }
];

/**
 * GET /api/content/list
 * 获取内容列表
 */
router.get('/list', (req: Request, res: Response) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      category, 
      type, 
      authorId,
      status = 'published'
    } = req.query;
    
    let filteredContents = contents.filter(content => content.status === status);
    
    // 按分类筛选
    if (category) {
      filteredContents = filteredContents.filter(content => 
        content.category === category
      );
    }
    
    // 按类型筛选
    if (type) {
      filteredContents = filteredContents.filter(content => 
        content.type === type
      );
    }
    
    // 按作者筛选
    if (authorId) {
      filteredContents = filteredContents.filter(content => 
        content.authorId === authorId
      );
    }
    
    // 分页
    const startIndex = (Number(page) - 1) * Number(pageSize);
    const endIndex = startIndex + Number(pageSize);
    const paginatedContents = filteredContents.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedContents,
        total: filteredContents.length,
        page: Number(page),
        pageSize: Number(pageSize),
        hasMore: endIndex < filteredContents.length
      }
    });
  } catch (error) {
    console.error('获取内容列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取内容列表失败'
    });
  }
});

/**
 * GET /api/content/:id
 * 获取内容详情
 */
router.get('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const content = contents.find(c => c.id === id);
    
    if (!content) {
      return res.status(404).json({
        success: false,
        error: '内容不存在'
      });
    }
    
    // 增加浏览量
    content.viewCount += 1;
    
    res.json({
      success: true,
      data: { content }
    });
  } catch (error) {
    console.error('获取内容详情失败:', error);
    res.status(500).json({
      success: false,
      error: '获取内容详情失败'
    });
  }
});

/**
 * POST /api/content
 * 创建内容
 */
router.post('/', (req: Request, res: Response) => {
  try {
    const {
      title,
      content,
      type,
      authorId,
      authorName,
      authorAvatar,
      tags,
      category,
      coverImage,
      summary
    } = req.body;
    
    if (!title || !content || !type || !authorId) {
      return res.status(400).json({
        success: false,
        error: '标题、内容、类型和作者ID为必填项'
      });
    }
    
    const newContent: Content = {
      id: Date.now().toString(),
      title,
      content,
      type,
      authorId,
      authorName: authorName || '匿名用户',
      authorAvatar: authorAvatar || 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=user%20avatar&image_size=square',
      tags: tags || [],
      category: category || '其他',
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      shareCount: 0,
      isLiked: false,
      isFavorited: false,
      publishTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      status: 'published',
      coverImage,
      summary
    };
    
    contents.push(newContent);
    
    res.status(201).json({
      success: true,
      data: { content: newContent }
    });
  } catch (error) {
    console.error('创建内容失败:', error);
    res.status(500).json({
      success: false,
      error: '创建内容失败'
    });
  }
});

/**
 * PUT /api/content/:id
 * 更新内容
 */
router.put('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const contentIndex = contents.findIndex(c => c.id === id);
    
    if (contentIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '内容不存在'
      });
    }
    
    const updatedContent = {
      ...contents[contentIndex],
      ...req.body,
      updateTime: new Date().toISOString()
    };
    
    contents[contentIndex] = updatedContent;
    
    res.json({
      success: true,
      data: { content: updatedContent }
    });
  } catch (error) {
    console.error('更新内容失败:', error);
    res.status(500).json({
      success: false,
      error: '更新内容失败'
    });
  }
});

/**
 * DELETE /api/content/:id
 * 删除内容
 */
router.delete('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const contentIndex = contents.findIndex(c => c.id === id);
    
    if (contentIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '内容不存在'
      });
    }
    
    contents.splice(contentIndex, 1);
    
    res.json({
      success: true,
      message: '内容删除成功'
    });
  } catch (error) {
    console.error('删除内容失败:', error);
    res.status(500).json({
      success: false,
      error: '删除内容失败'
    });
  }
});

/**
 * POST /api/content/:id/like
 * 点赞内容
 */
router.post('/:id/like', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const content = contents.find(c => c.id === id);
    
    if (!content) {
      return res.status(404).json({
        success: false,
        error: '内容不存在'
      });
    }
    
    if (content.isLiked) {
      content.likeCount -= 1;
      content.isLiked = false;
    } else {
      content.likeCount += 1;
      content.isLiked = true;
    }
    
    res.json({
      success: true,
      data: {
        isLiked: content.isLiked,
        likeCount: content.likeCount
      }
    });
  } catch (error) {
    console.error('点赞操作失败:', error);
    res.status(500).json({
      success: false,
      error: '点赞操作失败'
    });
  }
});

/**
 * POST /api/content/:id/favorite
 * 收藏内容
 */
router.post('/:id/favorite', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const content = contents.find(c => c.id === id);
    
    if (!content) {
      return res.status(404).json({
        success: false,
        error: '内容不存在'
      });
    }
    
    content.isFavorited = !content.isFavorited;
    
    res.json({
      success: true,
      data: {
        isFavorited: content.isFavorited
      }
    });
  } catch (error) {
    console.error('收藏操作失败:', error);
    res.status(500).json({
      success: false,
      error: '收藏操作失败'
    });
  }
});

/**
 * GET /api/content/categories
 * 获取内容分类列表
 */
router.get('/categories', (req: Request, res: Response) => {
  try {
    const categories = [
      { id: '1', name: '育儿知识', count: 156 },
      { id: '2', name: '营养喂养', count: 89 },
      { id: '3', name: '健康护理', count: 67 },
      { id: '4', name: '早教启蒙', count: 45 },
      { id: '5', name: '亲子互动', count: 78 },
      { id: '6', name: '产后恢复', count: 34 }
    ];
    
    res.json({
      success: true,
      data: { categories }
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取分类列表失败'
    });
  }
});

export default router;